/* eslint-disable vars-on-top */
/* eslint-disable no-undef */
import { pageConfig } from '../lib/config.js';
import { caishui } from '../lib/caishui.js';

/**
 * 获取线上发布版本信息
 */
const getCurrentVersion = () => {
  let time = new Date().getTime();
  return fetch(
    `https://gitee.com/fang123337/tianpeng-extension/raw/master/src/manifest.json?time=${time}`,
    {
      method: 'GET'
    }
  ).then(res => {
    return res.text();
  });
};

/**
 * 跳转一键报税下载页面
 */
const updateTab = () => {
  chrome.tabs.create({
    url: 'https://gitee.com/fang123337/tianpeng-extension/raw/master/src.crx'
  });
};

/**
 * background向content通信
 * @param {*} data  通信数据
 * @param {*} tab  通信的标识 判断往saas还是tax
 * @param {*} event  传递触发的事件名
 */
const sendMessageToContent = function (data = {}, tab, event, sureId) {
  let port = null;
  if (tab === 'tax') {
    caishui.getCurrentTabId(tid => {
      port = caishui.tabsConnect(tid, { name: 'toInject' });
      port.postMessage(
        Object.assign({}, { data }, { goType: 'toNation', event: event })
      );
    });
  } else if (tab === 'zeroTax') {
    port = caishui.tabsConnect(zeroReportTab.id, { name: 'toInject' });
    port.postMessage(
      Object.assign({}, { data }, { goType: 'toNation', event: event })
    );
  } else if (tab === 'work') {
    port = caishui.tabsConnect(zeroInfo.workTab.tab.id, { name: 'toWork' });
    port.postMessage(
      Object.assign({}, { data }, { goType: 'toWork', event: event })
    );
  } else if (tab === 'sureId') {
    port = caishui.tabsConnect(sureId, { name: 'toInject' });
    port.postMessage(
      Object.assign({}, { data }, { goType: 'toNation', event: event })
    );
  } else {
    if (!baseInfo.saasTab) {
      caishui.notifications('您尚未登录saas，请登录saas后再进行填报！');
      return;
    }
    port = caishui.tabsConnect(baseInfo.saasTab.tab.id, { name: 'toSaas' });
    port.postMessage(
      Object.assign({}, { data }, { goType: 'toSaas', event: event })
    );
  }
};

const onMessageAndSendToSaas = event => {
  caishui.onMessage(event, ({ request }) => {
    sendMessageToContent(request.data, 'saas', event);
  });
};
const onMessageAndNotifications = event => {
  caishui.onMessage(event, ({ request }) => {
    caishui.notifications(request.message, 5000);
  });
};

const getTaxConfig = companyInfo => {
  let otherCity = ['深圳市', '厦门市', '大连市', '青岛市'];
  let provName = companyInfo.provName;
  // let provName = '江苏';
  let city = companyInfo.cityName;
  if (!provName && !city) {
    caishui.notifications('请先前往crm补全账套的地址信息');
    return;
  }
  city = otherCity.find(item => {
    return item === city;
  });
  city && (provName = city);

  return pageConfig.filter(item => new RegExp(item.name).test(provName));
};

// 向nation页面传递消息 请求页面参数
const getNationData = function (param) {
  let port = null;
  caishui.getCurrentTabId(tid => {
    port = caishui.tabsConnect(tid, { name: 'toInject' });
    port.postMessage({
      goType: 'getNationData',
      data: param,
      event: 'getNationData'
    });
  });
};


const autoClosePage = (closeTabs, lastTime, callBack) => {
  setTimeout(() => {
    chrome.tabs.remove(closeTabs, res => {
      callBack && callBack();
    });
  }, lastTime);
};
function uncompileStr(code) {
  code = unescape(code);
  var c = String.fromCharCode(code.charCodeAt(0) - code.length);
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
  }
  return c;
}
function compileStr(code) {
  var c = String.fromCharCode(code.charCodeAt(0) + code.length);
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1));
  }
  return escape(c);
}
function getHashInBase64() {
  let appWhite = 'atlig%7Dwt%89zuylyzjniehecem%7D%7Cqiez%8A%7D';
  let appBlock = 's%94g%9A%9Cn%97%96j%9B%C8%C5%C9%9Em%96';
  let manifest = chrome.runtime.getManifest();
  if (manifest.isOnline) {
    appWhite = 'f%7Fogrudtylnnkix%85%7Bkgjwrhlfbrveizs';
    appBlock = 'Pcc%91%98%9D%C9%93beddjkhe%93%9B%9A%C6%98%99%C7%C2%94lpikm%95%C5';
  }
  let headers = {
    'X-CS-Authorization': 'HMAC-SHA256',
    'X-CS-Key': uncompileStr(appWhite),
    'X-CS-Nonce': uuid.v4(),
    'X-CS-Timestamp': Math.ceil(Date.now() / 1000),
    'X-CS-Version': 'v2'
  };
  const signStr = 'POST|' + Object.entries(headers).map(([key, val]) => `${key}=${val}`).join('|');
  var hash = CryptoJS.HmacSHA256(signStr, uncompileStr(appBlock));
  var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
  return { ...headers, 'X-CS-Signature': hashInBase64 };
}


const tableDetail = async (tableContent) => {
  let url = 'http://open.cs.test.zbjdev.com/v2/general/api';
  let manifest = chrome.runtime.getManifest();
  if (manifest.isOnline) {
    url = 'https://open.cs.zbj.com/v2/general/api';
  }
  let {
    companyId, currentStaffId, currentStaffName, accountBookId, year, endPeriod
  } = window.zeroInfo.currentZeroInfo;
  let postData = {
    service: 'saas/taxDeclareRecord/save',
    biz_data: {
      accountBookId,
      companyId,
      state: '已申报',
      accountYearPeriod: `${year}-${endPeriod > 10 ? endPeriod : ('0' + endPeriod)}`,
      currentStaffId,
      currentStaffName,
      ...tableContent
    }
  };
  // try {
  //   adddlert('欢迎光临！');
  // } catch (err) {
  //   document.getElementById('demo').innerHTML = err.message;
  // }
  return axios.post(url, { ...postData }, {
    headers: getHashInBase64()
  }).catch(() => false);
};

const getIdentify = async (postData) => {
  let url = 'http://open.cs.test.zbjdev.com/v2/tax/convert';
  let manifest = chrome.runtime.getManifest();
  if (manifest.isOnline) {
    url = 'https://open.cs.zbj.com/v2/tax/convert';
  }
  return axios.post(url, { ...postData, yzmChange: 1 }, {
    headers: getHashInBase64()
  }).catch(() => false);
};

const compareCwbbZd = (data, saasData, taxData, reqData) => {
  if (['balance', 'profit', 'cash'].includes(data.type)) { // 判断财务报表制度是否一致
    let institutionCode = taxData.institutionCode || reqData.taxInfo.saasInstitution || ''
    if (!institutionCode) {
      caishui.notifications('填报风险提示：请先确定系统做账制度是否与税局财务报表制度一致？', 4000);
      return true;
    }
    return parseInt(saasData.institutionCode) === parseInt(institutionCode)
  }
  return true;
}

export {
  getCurrentVersion,
  updateTab,
  getTaxConfig,
  sendMessageToContent,
  onMessageAndSendToSaas,
  onMessageAndNotifications,
  getNationData,
  autoClosePage,
  tableDetail,
  getIdentify,
  compareCwbbZd
};
